package com.gitee.wsl.collections.queue

import com.gitee.wsl.collections.list.toArray
import com.gitee.wsl.collections.set.api.SortedSet
import com.gitee.wsl.ext.base.Arrays
import com.gitee.wsl.ext.list.poll
import com.gitee.wsl.func.consumer.Consumer
import com.gitee.wsl.func.predicate.Predicate
import kotlin.jvm.JvmOverloads
import kotlin.jvm.Transient

/**
 * An unbounded priority [queue][Queue] based on a priority heap.
 * The elements of the priority queue are ordered according to their
 * [natural ordering][Comparable], or by a [Comparator]
 * provided at queue construction time, depending on which constructor is
 * used.  A priority queue does not permit `null` elements.
 * A priority queue relying on natural ordering also does not permit
 * insertion of non-comparable objects (doing so may result in
 * `ClassCastException`).
 *
 *
 * The *head* of this queue is the *least* element
 * with respect to the specified ordering.  If multiple elements are
 * tied for least value, the head is one of those elements -- ties are
 * broken arbitrarily.  The queue retrieval operations `poll`,
 * `remove`, `peek`, and `element` access the
 * element at the head of the queue.
 *
 *
 * A priority queue is unbounded, but has an internal
 * *capacity* governing the size of an array used to store the
 * elements on the queue.  It is always at least as large as the queue
 * size.  As elements are added to a priority queue, its capacity
 * grows automatically.  The details of the growth policy are not
 * specified.
 *
 *
 * This class and its iterator implement all of the
 * *optional* methods of the [Collection] and [ ] interfaces.  The Iterator provided in method [ ][.iterator] and the Spliterator provided in method [.spliterator]
 * are *not* guaranteed to traverse the elements of
 * the priority queue in any particular order. If you need ordered
 * traversal, consider using `Arrays.sort(pq.toArray())`.
 *
 *
 * **Note that this implementation is not synchronized.**
 * Multiple threads should not access a `PriorityQueue`
 * instance concurrently if any of the threads modifies the queue.
 * Instead, use the thread-safe [ ] class.
 *
 *
 * Implementation note: this implementation provides
 * O(log(n)) time for the enqueuing and dequeuing methods
 * (`offer`, `poll`, `remove()` and `add`);
 * linear time for the `remove(Object)` and `contains(Object)`
 * methods; and constant time for the retrieval methods
 * (`peek`, `element`, and `size`).
 *
 *
 * This class is a member of the
 * [
 * Java Collections Framework]({@docRoot}/java.base/java/util/package-summary.html#CollectionsFramework).
 *
 * @since 1.5
 * @author Josh Bloch, Doug Lea
 * @param <E> the type of elements held in this queue
</E> */
class PriorityQueue<E: Comparable<E>> : AbstractQueue<E> {
    /**
     * Priority queue represented as a balanced binary heap: the two
     * children of queue[n] are queue[2*n+1] and queue[2*(n+1)].  The
     * priority queue is ordered by comparator, or by the elements'
     * natural ordering, if comparator is null: For each node n in the
     * heap and each descendant d of n, n <= d.  The element with the
     * lowest value is in queue[0], assuming the queue is nonempty.
     */
    @Transient
    private lateinit var queue: Array<Any?> // non-private to simplify nested class access

    /**
     * The number of elements in the priority queue.
     */
    override var size: Int = 0

    /**
     * The comparator, or null if priority queue uses elements'
     * natural ordering.
     */
    // Conditionally serializable
    private val comparator: Comparator<in E>?

    /**
     * The number of times this priority queue has been
     * *structurally modified*.  See AbstractList for gory details.
     */
    @Transient
    private var modCount: Int = 0 // non-private to simplify nested class access

    /**
     * Creates a `PriorityQueue` with the default initial capacity and
     * whose elements are ordered according to the specified comparator.
     *
     * @param  comparator the comparator that will be used to order this
     * priority queue.  If `null`, the [         natural ordering][Comparable] of the elements will be used.
     * @since 1.8
     */
    constructor(comparator: Comparator<in E>) : this(DEFAULT_INITIAL_CAPACITY, comparator)

    /**
     * Creates a `PriorityQueue` with the specified initial capacity
     * that orders its elements according to the specified comparator.
     *
     * @param  initialCapacity the initial capacity for this priority queue
     * @param  comparator the comparator that will be used to order this
     * priority queue.  If `null`, the [         natural ordering][Comparable] of the elements will be used.
     * @throws IllegalArgumentException if `initialCapacity` is
     * less than 1
     */
    /**
     * Creates a `PriorityQueue` with the default initial
     * capacity (11) that orders its elements according to their
     * [natural ordering][Comparable].
     */
    /**
     * Creates a `PriorityQueue` with the specified initial
     * capacity that orders its elements according to their
     * [natural ordering][Comparable].
     *
     * @param initialCapacity the initial capacity for this priority queue
     * @throws IllegalArgumentException if `initialCapacity` is less
     * than 1
     */
    @JvmOverloads
    constructor(
        initialCapacity: Int = DEFAULT_INITIAL_CAPACITY,
        comparator: Comparator<in E>? = null,
    ) {
        // Note: This restriction of at least one is not actually needed,
        // but continues for 1.5 compatibility
        require(initialCapacity >= 1)
        this.queue = arrayOfNulls<Any>(initialCapacity)
        this.comparator = comparator
    }

    /**
     * Creates a `PriorityQueue` containing the elements in the
     * specified collection.  If the specified collection is an instance of
     * a [SortedSet] or is another `PriorityQueue`, this
     * priority queue will be ordered according to the same ordering.
     * Otherwise, this priority queue will be ordered according to the
     * [natural ordering][Comparable] of its elements.
     *
     * @param  c the collection whose elements are to be placed
     * into this priority queue
     * @throws ClassCastException if elements of the specified collection
     * cannot be compared to one another according to the priority
     * queue's ordering
     * @throws NullPointerException if the specified collection or any
     * of its elements are null
     */
    constructor(c: Collection<E>) {
        when (c) {
            is SortedSet<*> -> {
                this.comparator = c.comparator as Comparator<in E>?
                initElementsFromCollection(c)
            }

            is PriorityQueue<*> -> {
                this.comparator = c.comparator as Comparator<in E>?
                initFromPriorityQueue(c as PriorityQueue<E>)
            }
            else -> {
                this.comparator = null
                initFromCollection(c)
            }
        }
    }

    constructor(c: Array<out E>) {
        this.comparator = null
        initFromCollection(c.toList())
    }

    /**
     * Creates a `PriorityQueue` containing the elements in the
     * specified priority queue.  This priority queue will be
     * ordered according to the same ordering as the given priority
     * queue.
     *
     * @param  c the priority queue whose elements are to be placed
     * into this priority queue
     * @throws ClassCastException if elements of `c` cannot be
     * compared to one another according to `c`'s
     * ordering
     * @throws NullPointerException if the specified priority queue or any
     * of its elements are null
     */
//    constructor(c: PriorityQueue<out E>) {
//        this.comparator = c.comparator as Comparator<in E>?
//        initFromPriorityQueue(c)
//    }

    /**
     * Creates a `PriorityQueue` containing the elements in the
     * specified sorted set.   This priority queue will be ordered
     * according to the same ordering as the given sorted set.
     *
     * @param  c the sorted set whose elements are to be placed
     * into this priority queue
     * @throws ClassCastException if elements of the specified sorted
     * set cannot be compared to one another according to the
     * sorted set's ordering
     * @throws NullPointerException if the specified sorted set or any
     * of its elements are null
     */
//    constructor(c: java.util.SortedSet<out E?>) {
//        this.comparator = c.comparator() as java.util.Comparator<in E>?
//        initElementsFromCollection(c)
//    }

    private fun initFromPriorityQueue(c: PriorityQueue<out E>) {
        if (c::class == PriorityQueue::class) {
            this.queue = ensureNonEmpty(c.queue)
            this.size = c.size
        } else {
            initFromCollection(c)
        }
    }

    private fun initElementsFromCollection(c: Collection< E>) {
        this.queue = c.toArray()
        this.size = c.size
    }

    /**
     * Initializes queue array with elements from the given Collection.
     *
     * @param c the collection
     */
    private fun initFromCollection(c: Collection< E>) {
        initElementsFromCollection(c)
        heapify()
    }

    /**
     * Increases the capacity of the array.
     *
     * @param minCapacity the desired minimum capacity
     */
    private fun grow(minCapacity: Int) {
        val oldCapacity = queue.size
        // Double size if small; else grow by 50%
        val newCapacity: Int = Arrays.newLength(
            oldCapacity,
            minCapacity - oldCapacity,  /* minimum growth */
            if (oldCapacity < 64) oldCapacity + 2 else oldCapacity shr 1 /* preferred growth */
        )
        queue = queue.copyOf(newCapacity)
    }


    /**
     * Inserts the specified element into this priority queue.
     *
     * @return `true` (as specified by [Queue.offer])
     * @throws ClassCastException if the specified element cannot be
     * compared with elements currently in this priority queue
     * according to the priority queue's ordering
     * @throws NullPointerException if the specified element is null
     */
    override fun offer(e: E): Boolean {
        //if (e == null) throw NullPointerException()
        modCount++
        val i = size
        if (i >= queue.size) grow(i + 1)
        siftUp(i, e)
        size = i + 1
        return true
    }

    private fun indexOf(o: E?): Int {
        if (o != null) {
            val es = queue
            var i = 0
            val n = size
            while (i < n) {
                if (o == es[i]) return i
                i++
            }
        }
        return -1
    }

    /**
     * Removes a single instance of the specified element from this queue,
     * if it is present.  More formally, removes an element `e` such
     * that `o.equals(e)`, if this queue contains one or more such
     * elements.  Returns `true` if and only if this queue contained
     * the specified element (or equivalently, if this queue changed as a
     * result of the call).
     *
     * @param element element to be removed from this queue, if present
     * @return `true` if this queue changed as a result of the call
     */
    override fun remove(element: E): Boolean {
        val i = indexOf(element)
        if (i == -1)
            return false
        else {
            removeAt(i)
            return true
        }
    }

    /**
     * Identity-based version for use in Itr.remove.
     *
     * @param o element to be removed from this queue, if present
     */
    fun removeEq(o: E) {
        val es = queue
        var i = 0
        val n = size
        while (i < n) {
            if (o === es[i]) {
                removeAt(i)
                break
            }
            i++
        }
    }

    /**
     * Returns `true` if this queue contains the specified element.
     * More formally, returns `true` if and only if this queue contains
     * at least one element `e` such that `o.equals(e)`.
     *
     * @param element object to be checked for containment in this queue
     * @return `true` if this queue contains the specified element
     */
    override fun contains(element: E): Boolean {
        return indexOf(element) >= 0
    }

    /**
     * Returns an array containing all of the elements in this queue.
     * The elements are in no particular order.
     *
     *
     * The returned array will be "safe" in that no references to it are
     * maintained by this queue.  (In other words, this method must allocate
     * a new array).  The caller is thus free to modify the returned array.
     *
     *
     * This method acts as bridge between array-based and collection-based
     * APIs.
     *
     * @return an array containing all of the elements in this queue
     */
//    override fun toArray(): Array<Any> {
//        return queue.copyOf<Any?>(size)
//    }

    /**
     * Returns an array containing all of the elements in this queue; the
     * runtime type of the returned array is that of the specified array.
     * The returned array elements are in no particular order.
     * If the queue fits in the specified array, it is returned therein.
     * Otherwise, a new array is allocated with the runtime type of the
     * specified array and the size of this queue.
     *
     *
     * If the queue fits in the specified array with room to spare
     * (i.e., the array has more elements than the queue), the element in
     * the array immediately following the end of the collection is set to
     * `null`.
     *
     *
     * Like the [.toArray] method, this method acts as bridge between
     * array-based and collection-based APIs.  Further, this method allows
     * precise control over the runtime type of the output array, and may,
     * under certain circumstances, be used to save allocation costs.
     *
     *
     * Suppose `x` is a queue known to contain only strings.
     * The following code can be used to dump the queue into a newly
     * allocated array of `String`:
     *
     * <pre> `String[] y = x.toArray(new String[0]);`</pre>
     *
     * Note that `toArray(new Object[0])` is identical in function to
     * `toArray()`.
     *
     * @param a the array into which the elements of the queue are to
     * be stored, if it is big enough; otherwise, a new array of the
     * same runtime type is allocated for this purpose.
     * @return an array containing all of the elements in this queue
     * @throws ArrayStoreException if the runtime type of the specified array
     * is not a supertype of the runtime type of every element in
     * this queue
     * @throws NullPointerException if the specified array is null
     */
//    override fun <T> toArray(a: Array<T?>): Array<T?> {
//        val size = this.size
//        if (a.size < size)  // Make a new array of a's runtime type, but my contents:
//            return java.util.Arrays.copyOf<Any?, Any?>(queue, size, a.javaClass) as Array<T?>
//        java.lang.System.arraycopy(queue, 0, a, 0, size)
//        if (a.size > size) a[size] = null
//        return a
//    }

    /**
     * Returns an iterator over the elements in this queue. The iterator
     * does not return the elements in any particular order.
     *
     * @return an iterator over the elements in this queue
     */
    override fun iterator(): MutableIterator<E> {
        return Itr()
    }

    // prevent access constructor creation
    private inner class Itr : MutableIterator<E> {
        /**
         * Index (into queue array) of element to be returned by
         * subsequent call to next.
         */
        private var cursor = 0

        /**
         * Index of element returned by most recent call to next,
         * unless that element came from the forgetMeNot list.
         * Set to -1 if element is deleted by a call to remove.
         */
        private var lastRet = -1

        /**
         * A queue of elements that were moved from the unvisited portion of
         * the heap into the visited portion as a result of "unlucky" element
         * removals during the iteration.  (Unlucky element removals are those
         * that require a siftup instead of a siftdown.)  We must visit all of
         * the elements in this list to complete the iteration.  We do this
         * after we've completed the "normal" iteration.
         *
         * We expect that most iterations, even those involving removals,
         * will not need to store elements in this field.
         */
        private var forgetMeNot: ArrayDeque<E>? = null

        /**
         * Element returned by the most recent call to next iff that
         * element was drawn from the forgetMeNot list.
         */
        private var lastRetElt: E? = null

        /**
         * The modCount value that the iterator believes that the backing
         * Queue should have.  If this expectation is violated, the iterator
         * has detected concurrent modification.
         */
        private var expectedModCount = modCount

        override fun hasNext(): Boolean {
            return cursor < size || (forgetMeNot != null && !forgetMeNot!!.isEmpty())
        }

        override fun next(): E {
            if (expectedModCount != modCount) throw ConcurrentModificationException()
            if (cursor < size) return queue[(cursor++).also { lastRet = it }] as E
            if (forgetMeNot != null) {
                lastRet = -1
                lastRetElt = forgetMeNot!!.poll()
                if (lastRetElt != null) return lastRetElt as E
            }
            throw NoSuchElementException()
        }

        override fun remove() {
            if (expectedModCount != modCount) throw ConcurrentModificationException()
            if (lastRet != -1) {
                val moved = this@PriorityQueue.removeAt(lastRet)
                lastRet = -1
                if (moved == null) cursor--
                else {
                    if (forgetMeNot == null) forgetMeNot = ArrayDeque<E>()
                    forgetMeNot!!.add(moved)
                }
            } else if (lastRetElt != null) {
                this@PriorityQueue.removeEq(lastRetElt as E)
                lastRetElt = null
            } else {
                throw IllegalStateException()
            }
            expectedModCount = modCount
        }
    }


    /**
     * Removes all of the elements from this priority queue.
     * The queue will be empty after this call returns.
     */
    override fun clear() {
        modCount++
        val es = queue
        var i = 0
        val n = size
        while (i < n) {
            es[i] = null
            i++
        }
        size = 0
    }

    override fun pollOrNull(): E? {
        val es: Array<Any?> = queue
        val result: E? = es[0] as E?

        if (result != null) {
            modCount++
            val n: Int
            val x = es[((--size).also { n = it })] as E
            es[n] = null
            if (n > 0) {
                if (comparator == null)
                    siftDownComparable(0, x, es, n)
                else
                    siftDownUsingComparator(0, x, es, n, comparator)
            }
        }
        return result
    }


    override fun peekOrNull(): E?  = if(queue.isEmpty()) null else queue[0] as E?

    /**
     * Removes the ith element from queue.
     *
     * Normally this method leaves the elements at up to i-1,
     * inclusive, untouched.  Under these circumstances, it returns
     * null.  Occasionally, in order to maintain the heap invariant,
     * it must swap a later element of the list with one earlier than
     * i.  Under these circumstances, this method returns the element
     * that was previously at the end of the list and is now at some
     * position before i. This fact is used by iterator.remove so as to
     * avoid missing traversing elements.
     */
    fun removeAt(i: Int): E? {
        // assert i >= 0 && i < size;
        val es = queue
        modCount++
        val s = --size
        if (s == i)  // removed last element
            es[i] = null
        else {
            val moved = es[s] as E
            es[s] = null
            siftDown(i, moved)
            if (es[i] == moved) {
                siftUp(i, moved)
                if (es[i] != moved) return moved
            }
        }
        return null
    }

    /**
     * Inserts item x at position k, maintaining heap invariant by
     * promoting x up the tree until it is greater than or equal to
     * its parent, or is the root.
     *
     * To simplify and speed up coercions and comparisons, the
     * Comparable and Comparator versions are separated into different
     * methods that are otherwise identical. (Similarly for siftDown.)
     *
     * @param k the position to fill
     * @param x the item to insert
     */
    private fun siftUp(k: Int, x: E) {
        if (comparator != null) siftUpUsingComparator(k, x, queue, comparator)
        else siftUpComparable(k, x, queue)
    }

    /**
     * Inserts item x at position k, maintaining heap invariant by
     * demoting x down the tree repeatedly until it is less than or
     * equal to its children or is a leaf.
     *
     * @param k the position to fill
     * @param x the item to insert
     */
    private fun siftDown(k: Int, x: E) {
        if (comparator != null) siftDownUsingComparator(k, x, queue, size, comparator)
        else siftDownComparable(k, x, queue, size)
    }

    /**
     * Establishes the heap invariant (described above) in the entire tree,
     * assuming nothing about the order of the elements prior to the call.
     * This classic algorithm due to Floyd (1964) is known to be O(size).
     */
    private fun heapify() {
        val es = queue
        val n = size
        var i = (n ushr 1) - 1
        if (comparator == null)
            while (i >= 0) {
               siftDownComparable(i, es[i] as E , es, n)
               i--
            }
        else
            while (i >= 0) {
            siftDownUsingComparator<E>(i, es[i] as E, es, n, comparator)
            i--
        }
    }

    /**
     * Returns the comparator used to order the elements in this
     * queue, or `null` if this queue is sorted according to
     * the [natural ordering][Comparable] of its elements.
     *
     * @return the comparator used to order this queue, or
     * `null` if this queue is sorted according to the
     * natural ordering of its elements
     */
//    fun comparator(): java.util.Comparator<in E>? {
//        return comparator
//    }

    /**
     * Saves this queue to a stream (that is, serializes it).
     *
     * @param s the stream
     * @throws java.io.IOException if an I/O error occurs
     * @serialData The length of the array backing the instance is
     * emitted (int), followed by all of its elements
     * (each an `Object`) in the proper order.
     */

//    @Throws(IOException::class)
//    private fun writeObject(s: java.io.ObjectOutputStream) {
//        // Write out element count, and any hidden stuff
//        s.defaultWriteObject()
//
//        // Write out array length, for compatibility with 1.5 version
//        s.writeInt(max(2, size + 1))
//
//        // Write out all elements in the "proper order".
//        val es = queue
//        var i = 0
//        val n = size
//        while (i < n) {
//            s.writeObject(es[i])
//            i++
//        }
//    }

    /**
     * Reconstitutes the `PriorityQueue` instance from a stream
     * (that is, deserializes it).
     *
     * @param s the stream
     * @throws ClassNotFoundException if the class of a serialized object
     * could not be found
     * @throws java.io.IOException if an I/O error occurs
     */
//    @java.io.Serial
//    @Throws(java.io.IOException::class, java.lang.ClassNotFoundException::class)
//    private fun readObject(s: java.io.ObjectInputStream) {
//        // Read in size, and any hidden stuff
//        s.defaultReadObject()
//
//        // Read in (and discard) array length
//        s.readInt()
//
//        SharedSecrets.getJavaObjectInputStreamAccess().checkArray(s, Array<Any>::class.java, size)
//        queue = kotlin.arrayOfNulls<Any>(max(size, 1))
//        val es: Array<Any?> = queue
//
//        // Read in all elements.
//        var i = 0
//        val n = size
//        while (i < n) {
//            es[i] = s.readObject()
//            i++
//        }
//
//        // Elements are guaranteed to be in "proper order", but the
//        // spec has never explained what that might be.
//        heapify()
//    }

    /**
     * Creates a *[late-binding](Spliterator.html#binding)*
     * and *fail-fast* [Spliterator] over the elements in this
     * queue. The spliterator does not traverse elements in any particular order
     * (the [ORDERED][Spliterator.ORDERED] characteristic is not reported).
     *
     *
     * The `Spliterator` reports [Spliterator.SIZED],
     * [Spliterator.SUBSIZED], and [Spliterator.NONNULL].
     * Overriding implementations should document the reporting of additional
     * characteristic values.
     *
     * @return a `Spliterator` over the elements in this queue
     * @since 1.8
     */
//    override fun spliterator(): Spliterator<E?> {
//        return PriorityQueueSpliterator(0, -1, 0)
//    }
//
//    internal inner class PriorityQueueSpliterator(
//// current index, modified on advance/split
//        private var index: Int, // -1 until first use
//        private var fence: Int, expectedModCount: Int,
//    ) : Spliterator<E?> {
//        private var expectedModCount: Int // initialized when fence set
//
//        /** Creates new spliterator covering the given range.  */
//        init {
//            this.fence = fence
//            this.expectedModCount = expectedModCount
//        }
//
//        private fun getFence(): Int { // initialize fence to size on first use
//            var hi: Int
//            if ((fence.also { hi = it }) < 0) {
//                expectedModCount = modCount
//                fence = size
//                hi = fence
//            }
//            return hi
//        }
//
//        override fun trySplit(): PriorityQueueSpliterator? {
//            val hi = getFence()
//            val lo = index
//            val mid = (lo + hi) ushr 1
//            return if (lo >= mid) null else PriorityQueueSpliterator(lo, mid.also { index = it }, expectedModCount)
//        }
//
//        override fun forEachRemaining(action: java.util.function.Consumer<in E?>) {
//            if (action == null) throw java.lang.NullPointerException()
//            if (fence < 0) {
//                fence = size
//                expectedModCount = modCount
//            }
//            val es = queue
//            var i: Int
//            val hi: Int
//            var e: E?
//            i = index
//            index = fence.also { hi = it }
//            while (i < hi) {
//                if (((es[i] as E?).also { e = it }) == null) break // must be CME
//
//                action.accept(e)
//                i++
//            }
//            if (modCount != expectedModCount) throw java.util.ConcurrentModificationException()
//        }
//
//        override fun tryAdvance(action: java.util.function.Consumer<in E?>): Boolean {
//            if (action == null) throw java.lang.NullPointerException()
//            if (fence < 0) {
//                fence = size
//                expectedModCount = modCount
//            }
//            val i: Int
//            if ((index.also { i = it }) < fence) {
//                index = i + 1
//                val e: E?
//                if (((queue[i] as E?).also { e = it }) == null
//                    || modCount != expectedModCount
//                ) throw java.util.ConcurrentModificationException()
//                action.accept(e)
//                return true
//            }
//            return false
//        }
//
//        override fun estimateSize(): Long {
//            return (getFence() - index).toLong()
//        }
//
//        override fun characteristics(): Int {
//            return java.util.Spliterator.SIZED or java.util.Spliterator.SUBSIZED or java.util.Spliterator.NONNULL
//        }
//    }

    /**
     * @throws NullPointerException {@inheritDoc}
     */
    fun removeIf(filter: Predicate<in E>): Boolean {
        return bulkRemove(filter)
    }

    /**
     * @throws NullPointerException {@inheritDoc}
     */
    override fun removeAll(elements: Collection<E>): Boolean {
        return bulkRemove(Predicate { e: E -> elements.contains(e) })
    }

    /**
     * @throws NullPointerException {@inheritDoc}
     */
    override fun retainAll(elements: Collection<E>): Boolean {
        return bulkRemove(Predicate { e: E -> !elements.contains(e) })
    }

    /** Implementation of bulk remove methods.  */
    private fun bulkRemove(filter: Predicate<in E>): Boolean {
        val expectedModCount = ++modCount
        val es = queue
        val end = size
        // Optimize for initial run of survivors
        var i: Int = 0
        while (i < end && !filter.test(es[i] as E)) {
            i++
        }
        if (i >= end) {
            if (modCount != expectedModCount) throw ConcurrentModificationException()
            return false
        }
        // Tolerate predicates that reentrantly access the collection for
        // read (but writers still get CME), so traverse once to find
        // elements to delete, a second pass to physically expunge.
        val beg = i
        val deathRow = nBits(end - beg)
        deathRow[0] = 1L // set bit 0
        i = beg + 1
        while (i < end) {
            if (filter.test(es[i] as E)) setBit(deathRow, i - beg)
            i++
        }
        if (modCount != expectedModCount) throw ConcurrentModificationException()
        var w = beg
        i = beg
        while (i < end) {
            if (isClear(deathRow, i - beg)) es[w++] = es[i]
            i++
        }
        i = w.also { size = it }
        while (i < end) {
            es[i] = null
            i++
        }
        heapify()
        return true
    }

    /**
     * @throws NullPointerException {@inheritDoc}
     */
    fun forEach(action: Consumer<in E?>) {
        val expectedModCount = modCount
        val es = queue
        var i = 0
        val n = size
        while (i < n) {
            action.accept(es[i] as E?)
            i++
        }
        if (expectedModCount != modCount) throw ConcurrentModificationException()
    }


    companion object {

        private const val DEFAULT_INITIAL_CAPACITY = 11

        /** Ensures that queue[0] exists, helping peek() and poll().  */
        private fun ensureNonEmpty(es: Array<Any?>): Array<Any?> {
            return if (es.isNotEmpty()) es else kotlin.arrayOfNulls<Any>(1)
        }

        private fun <T: Comparable<T>> siftUpComparable(k: Int, x: T, es: Array<Any?>) {
            var k = k
            val key = x
            while (k > 0) {
                val parent = (k - 1) ushr 1
                val e = es[parent] as T
                if (key >= e) break
                es[k] = e
                k = parent
            }
            es[k] = key
        }

        private fun <T> siftUpUsingComparator(
            k: Int, x: T, es: Array<Any?>, cmp: Comparator<in T>,
        ) {
            var k = k
            while (k > 0) {
                val parent = (k - 1) ushr 1
                val e = es[parent]
                if (cmp.compare(x, e as T) >= 0) break
                es[k] = e
                k = parent
            }
            es[k] = x!!
        }

        private fun <T: Comparable<T>> siftDownComparable(k: Int, x: T, es: Array<Any?>, n: Int) {
            // assert n > 0;
            var k = k
            val key = x
            val half = n ushr 1 // loop while a non-leaf
            while (k < half) {
                var child = (k shl 1) + 1 // assume left child is least
                var c = es[child] as T
                val right = child + 1
                if (right < n && c > es[right] as T)
                    c = es[right.also { child = it }] as T
                if ( key <= c ) break
                es[k] = c
                k = child
            }
            es[k] = key
        }

        private fun <T> siftDownUsingComparator(
            k: Int, x: T, es: Array<Any?>, n: Int, cmp: Comparator<in T>,
        ) {
            // assert n > 0;
            var k = k
            val half = n ushr 1
            while (k < half) {
                var child = (k shl 1) + 1
                var c = es[child]
                val right = child + 1
                if (right < n && cmp.compare(c as T, es[right] as T) > 0) c = es[right.also { child = it }]
                if (cmp.compare(x, c as T) <= 0) break
                es[k] = c
                k = child
            }
            es[k] = x!!
        }

        // A tiny bit set implementation
        private fun nBits(n: Int): LongArray {
            return LongArray(((n - 1) shr 6) + 1)
        }

        private fun setBit(bits: LongArray, i: Int) {
            bits[i shr 6] = bits[i shr 6] or (1L shl i)
        }

        private fun isClear(bits: LongArray, i: Int): Boolean {
            return (bits[i shr 6] and (1L shl i)) == 0L
        }
    }
}


fun PriorityQueue(intArray: IntArray) = PriorityQueue(intArray.toList())

fun PriorityQueue(array: FloatArray) = PriorityQueue(array.toList())

fun PriorityQueue(array: DoubleArray) = PriorityQueue(array.toList())

fun PriorityQueue(array: ShortArray) = PriorityQueue(array.toList())

fun PriorityQueue(array: LongArray) = PriorityQueue(array.toList())